# -*- coding:utf-8 -*-

from dbbasic import dbMgr
from Models import Mail

def save(mail):
	if isinstance(mail,Mail):
		with dbMgr() as cursor:
			#cursor.execute('create table mail(id integer primary key autoincrement,receiver varchar(200), sub varchar(200),content varchar(200),sendFlag boolean)')
			cursor.execute('insert into mail values(null,?,?,?,?)', (mail.receiver,mail.sub,mail.content,mail.sendFlag))

def update(mail):
	if mail.id == None:
		print 'id is none, save first'
		return
	with dbMgr() as cursor:
		cursor.execute('update mail set receiver=?,sub=?,content=?,sendFlag=? where id=?', (mail.receiver,mail.sub,mail.content,mail.sendFlag,mail.id))

def get(mailId):
	if isinstance(mailId, int):
		with dbMgr() as cursor:
			cursor.execute('select * from mail where id=?', (mailId,))
			value = cursor.fetchone()
			if value == None:
				return None
			mail = Mail(*value[1:])
			mail.id = value[0]
			return mail
			
		
def list(pageNo=1, pageSize=1000000,**condition):
	con = ''
	for c in condition:
		if isinstance(condition[c], int):
			con = con + '%s=%d and ' % (c, condition[c])
		if isinstance(condition[c], str):
			con = con + '%s=\'%s\' and ' % (c, condition[c])
	if not len(con) == 0:
		con = ' where ' + con
	con = con[0:len(con)-4]
	with dbMgr() as cursor:
		cursor.execute('select * from mail' + con +' order by id desc limit ? offset ?',  (pageSize, (pageNo - 1) * pageSize))
		values = cursor.fetchall()
		mails = []
	
		for v in values:
			mail = Mail(*v[1:])
			mail.id = v[0]
			mails.append(mail)
		return mails
		

